package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/19
 */
@WebFilter(filterName = "AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        Object user = request.getSession().getAttribute("user");
        if(user!=null){
            chain.doFilter(req, resp);
            return;
        }
        UserService userService = new UserServiceImpl();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if("userinfo".equals(cookie.getName())){
                    String value = cookie.getValue();
                    String userInfo = Base64Utils.decode(value);
                    String[] strs = userInfo.split("#");
                    if(strs!=null&&strs.length==2){
                        User login = userService.login(strs[0], strs[1]);
                        request.getSession().setAttribute("user", login);
                    }

                    break;
                }
            }
        }


        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
